//
//  NSDictionary+Addtions.m
//  Backhome
//
//  Created by vbn on 2018/8/13.
//  Copyright © 2018年 SmartHome. All rights reserved.
//

#import "NSDictionary+KNAddtions.h"

@implementation NSDictionary (KNAddtions)

- (NSMutableDictionary *)KNToMutableDictionary {
    NSMutableDictionary * mutable = @{}.mutableCopy;
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSObject class]] && [obj respondsToSelector:@selector(mutableCopyWithZone:)]) {
            NSObject *mutableObj = [obj mutableCopy];
            [mutable setObject:mutableObj forKey:key];
            if ([mutableObj isKindOfClass:[NSMutableDictionary class]]) {
                [self KNConvertToMutableDict:mutableObj];
            } else if ([mutableObj isKindOfClass:[NSMutableArray class]]) {
                [self KNConvertToMutableArray:mutableObj];
            }
        } else {
            [mutable setObject:obj forKey:key];
        }
        
    }];
    return mutable;
}

- (void)KNConvertToMutableDict:(NSMutableDictionary *)mutableDict {
    [mutableDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSObject class]] && [obj respondsToSelector:@selector(mutableCopyWithZone:)]) {
            NSObject *mutableObj = [obj mutableCopy];
            [mutableDict setObject:mutableObj forKey:key];
            if ([mutableObj isKindOfClass:[NSMutableDictionary class]]) {
                [self KNConvertToMutableDict:mutableObj];
            } else if ([mutableObj isKindOfClass:[NSMutableArray class]]) {
                [self KNConvertToMutableArray:mutableObj];
            }
        } else {
            [mutableDict setObject:obj forKey:key];
        }
    }];
}

- (void)KNConvertToMutableArray:(NSMutableArray *)mutableArray {
    for (int i = 0; i<mutableArray.count; i++) {
        NSObject *obj = mutableArray[i];
        if ([obj respondsToSelector:@selector(mutableCopyWithZone:)]) {
            NSObject *mutalbeObj = [obj mutableCopy];
            [mutableArray replaceObjectAtIndex:i withObject:mutalbeObj];
            if ([mutalbeObj isKindOfClass:[NSMutableDictionary class]]) {
                [self KNConvertToMutableDict:mutalbeObj];
            } else if ([mutalbeObj isKindOfClass:[NSMutableArray class]]) {
                [self KNConvertToMutableArray:mutalbeObj];
            }
        }
        
    }
}
@end
